package com.aifeng.fragment

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.aifeng.base.*
import com.aifeng.common_ui.base.find
import com.aifeng.common_ui.base.getColorEx
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.base.startActivityEx
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyGridLayoutManager
import com.aifeng.hassan_food.NoticeActivity
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.SearchActivity
import com.aifeng.hassan_food.login.LoginActivity
import com.aifeng.hassan_food.sale.DetailActivity
import com.aifeng.model.CommonData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.view.ImageResourceAdapter
import com.aifeng.view.ImageResourceViewHolder
import com.aifeng.viewmodel.HomeViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import kotlinx.android.synthetic.main.fragment_main_one.*
import net.idik.lib.slimadapter.SlimAdapter
import org.koin.androidx.viewmodel.ext.android.getViewModel

class MainOneFragment : BaseFragment() {

    private lateinit var mViewPager: BannerViewPager<CommonData, ImageResourceViewHolder>
    private lateinit var mLinearAdapter: SlimAdapter
    private val mList = ArrayList<CommonData>()
    private val mListHot = ArrayList<CommonData>()
    private val mBannerList = ArrayList<CommonData>()
    private val mNoticeList = ArrayList<String>()

    //调用这个方法切换时不会释放掉Fragment
    override fun setMenuVisibility(menuVisible: Boolean) {
        super.setMenuVisibility(menuVisible)
        this.view?.visibility = if (menuVisible) View.VISIBLE else View.GONE

        if (menuVisible) {
            if (mBannerList.isNotEmpty()) mViewPager.startLoop()
            if (mNoticeList.isNotEmpty()) {
                one_notice.apply {
                    if (count > 1) startViewAnimator()
                }
            }
        } else {
            if (mBannerList.isNotEmpty()) mViewPager.stopLoop()
            if (mNoticeList.isNotEmpty()) one_notice.stopViewAnimator()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_main_one, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initTitle()

        one_swipe.isRefreshing = true
        getData()
        getHotData()
    }

    override fun getViewModel() = getViewModel<HomeViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle() {
        initViewPager()
        one_swipe.refresh {
            getData()
            getHotData()
        }

        one_hot.apply {
            layoutManager = LinearLayoutManager(
                activity!!,
                LinearLayoutManager.HORIZONTAL,
                false
            )
            mLinearAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_one_list) { inner, jector ->

                    val index = mListHot.indexOf(inner)
                    val isFirst = index == 0
                    val isLast = index == mListHot.size - 1

                    jector.text(R.id.item_one_name, inner.goodname)
                        .text(
                            R.id.item_one_price,
                            setHtmlSmall(
                                "¥ ${if (getIContext().isLogin) inner.price.formatDecimal() else inner.orgprice.formatDecimal()}",
                                "¥"
                            )
                        )
                        .with<TextView>(R.id.item_one_orgin) {
                            it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                            it.text = "¥ ${inner.orgprice.formatDecimalWhenHave()}"
                        }
                        .with<ImageView>(R.id.item_one_img) {
                            val imgs = inner.goodimg.split(",")
                            it.loadTopImage(
                                dpWidth = 186f,
                                dpHeight = 155f,
                                url = imgs[0].scaleImage(400, 400)
                            )
                        }
                        .visibility(
                            R.id.item_one_orgin,
                            if (getIContext().isLogin) View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_one_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_one_divider1,
                            if (isFirst) View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_one_divider2,
                            if (isLast) View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_one_add) { view ->
                            if (getIContext().isLogin) {
                                getViewModel().addToCar(
                                    inner.id,
                                    getString("userId"),
                                    1
                                )
                                    .bindLifeCycle(getLifecycleOwner())
                                    .subscribeByNoError(
                                        event = getViewModel(),
                                        onSuccess = {
                                            val position = IntArray(2)
                                            view.getLocationInWindow(position)
                                            LiveEventBus.get("carList").post("refresh")
                                            LiveEventBus.get("updateNum")
                                                .post("${position[0]},${position[1]},$it")
                                        }
                                    )
                            } else {
                                startActivityEx<LoginActivity>()
                            }
                        }
                        .clicked(R.id.item_one) {
                            startActivityEx<DetailActivity>("id" to inner.id)
                        }
                }
                .attachTo(this)
        }

        one_list.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyGridLayoutManager(activity!!, 2)
            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_three_grid) { inner, jector ->
                    jector.text(R.id.item_three_name, inner.goodname)
                        .text(
                            R.id.item_three_price,
                            setHtmlSmall(
                                "¥ ${if (getIContext().isLogin) inner.price.formatDecimal() else inner.orgprice.formatDecimal()}",
                                "¥"
                            )
                        )
                        .with<TextView>(R.id.item_three_orgin) {
                            it.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                            it.text = "¥ ${inner.orgprice.formatDecimalWhenHave()}"
                        }
                        .with<ImageView>(R.id.item_three_img) {
                            val imgs = inner.goodimg.split(",")
                            it.loadImage(url = imgs[0].scaleImage(320, 320))
                        }
                        .visibility(
                            R.id.item_three_orgin,
                            if (getIContext().isLogin) View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_three_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_three_add) { view ->
                            if (getIContext().isLogin) {
                                getViewModel().addToCar(
                                    inner.id,
                                    getString("userId"),
                                    1
                                )
                                    .bindLifeCycle(getLifecycleOwner())
                                    .subscribeByNoError(
                                        event = getViewModel(),
                                        onSuccess = {
                                            val position = IntArray(2)
                                            view.getLocationInWindow(position)
                                            LiveEventBus.get("carList").post("refresh")
                                            LiveEventBus.get("updateNum")
                                                .post("${position[0]},${position[1]},$it")
                                        }
                                    )
                            } else {
                                startActivityEx<LoginActivity>()
                            }
                        }
                        .clicked(R.id.item_three) {
                            startActivityEx<DetailActivity>("id" to inner.id)
                        }
                }
                .attachTo(this)
        }

        one_hint.oneClick { startActivityEx<SearchActivity>() }
        one_notice.oneClick { startActivityEx<NoticeActivity>() }

        observe("mainLogin") {
            mLinearAdapter.notifyDataSetChanged()
            mAdapter.notifyDataSetChanged()
        }
    }

    private fun initViewPager() {
        mViewPager = find(R.id.one_banner)
        mViewPager.apply {
            adapter = ImageResourceAdapter()
            setIndicatorStyle(IndicatorStyle.ROUND_RECT)
            setIndicatorSlideMode(IndicatorSlideMode.SCALE)
            setIndicatorSliderGap(dp2px(4f))
            setIndicatorHeight(dp2px(4f))
            setIndicatorSliderColor(
                activity!!.getColorEx(R.color.white),
                activity!!.getColorEx(R.color.colorAccent)
            )
            setIndicatorSliderWidth(dp2px(4f), dp2px(10f))
            setPageMargin(dp2px(20f))
            setInterval(5000)
            setScrollDuration(500)
            setOnPageClickListener {
                when (mBannerList[it].type) {
                    "goods" -> {
                        startActivityEx<DetailActivity>(
                            "id" to mBannerList[it].typeid
                        )
                    }
                }
            }
        }.create()
    }

    private fun getNoticeData() {
        getViewModel().getNoticeList(1)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { data ->
                    mNoticeList.clear()
                    data.mapTo(mNoticeList) { it.title }

                    one_notice.apply {
                        setDatas(mNoticeList)
                        setItemOnClickListener { _, _ ->
                            startActivityEx<NoticeActivity>()
                        }
                        if (mNoticeList.size < 2) stopViewAnimator()
                    }
                }
            )
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().banner()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mBannerList.clear()
                    mBannerList.addItems(it)
                    mViewPager.refreshData(mBannerList)
                },
                onFinally = { getNoticeData() }
            )
    }

    private fun getHotData() {
        getViewModel().getHotList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mListHot.clear()
                    mListHot.addItems(it)
                    mLinearAdapter.updateData(mListHot)
                },
                onFinally = { getRecommendData() }
            )
    }

    private fun getRecommendData() {
        getViewModel().getRecommendList(getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.clear()
                    mList.addItems(it)
                    mAdapter.updateData(mList)
                },
                onFinally = { one_swipe.isRefreshing = false }
            )
    }

    override fun onPause() {
        super.onPause()
        mViewPager.stopLoop()
        one_notice.stopViewAnimator()
    }

    override fun onResume() {
        super.onResume()
        mViewPager.startLoop()
        one_notice.apply {
            if (count > 1) startViewAnimator()
        }
    }

}
